import { parse, format as formatDate } from 'date-fns'


const  number = function({value}){
    return /^[0-9]+$/.test(String(value))
}

const required = function({value}){
    if (value === undefined || value === null || value === '') {
        return false;
    }
    return !! String(value).trim().length;
}

const length = function({value,min,max}){
    let reg = '';
    if(min !== undefined && max === undefined){
        if(!number({value:min})) return false;
        reg = `^.{${min},${max}}$`;
    }
    else if(min === undefined && max !== undefined){
        if(!number({value:max})) return false;
        reg = `^.{0,${max}}$`;
    }
    else if(min !== undefined && max !== undefined){
        if(!number({value:min})||!number({value:max})) return false;
        reg = `^.{${min},${max}}$`;
    }
    return new RegExp(reg).test(value);
}

const url = function({value}){
    return /^((ht|f)tps?):\/\/[\w\-]+(\.[\w\-]+)+([\w\-\.,@?^=%&:\/~\+#]*[\w\-\@?^=%&\/~\+#])?$/.test(value);
}

const email = function({value}){
    return /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/.test(value)
}

const date = ({value,format = 'YYYY-MM-DD'}) => {
    const _value = parse(value, format, new Date())
    if (value !== formatDate(_value, format)) {
        return false
    }
    return true;
}

const validator = async function({value,validate}){
    let result = await validate(value);
    return result;
}

export default {
    number,
    required,
    email,
    date,
    length,
    validator,
    url
}